package com.itmentu.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * 死信队列的配置
 */
@Configuration
public class DeadExchangeConfig {

    /**
     * 创建交换机
     */
    @Bean
    public Exchange deadLetterExchange() {
        return ExchangeBuilder.directExchange("dead_letter_exchange").durable(true).build();
    }

    /**
     * 死信队列
     * @return
     */
    @Bean
    public Queue deadLetterQueue() {
        return QueueBuilder.durable("dead_letter_queue")
                //设置队列过期时间
                .ttl(1000*60)
                //死信队列Exchange
                .deadLetterExchange("dead_letter_exchange")
                //如果变成死信队列，则转发到交换机，并且路由key=general
                .deadLetterRoutingKey("general")
                .build();
    }

    /**
     * 死信队列绑定到死信交换器上.
     * @return the binding
     */
    @Bean
    public Binding deadLetterBinding(@Qualifier("deadLetterQueue")Queue queue,
                                     @Qualifier("deadLetterExchange")Exchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with("dead").noargs();
    }

    /**
     * 普通队列，用于接收死信队列转发到交换机的数据
     * @return
     */
    @Bean
    public Queue generalQueue() {
        return QueueBuilder.durable("general_queue").build();
    }

    /**
     * 将重定向队列通过routingKey(TKEY_R)绑定到死信队列的Exchange上
     * @return the binding
     */
    @Bean
    public Binding redirectBinding(@Qualifier("generalQueue")Queue queue,
                                   @Qualifier("deadLetterExchange")Exchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with("general").noargs();
    }
}